package com.wjl.shop.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

@Configuration
public class MyCacheManager
{
    @Bean
    public RedisCacheManager cacheManager(RedisTemplate<String, Object> template)
    {
        RedisCacheConfiguration defaultCacheConfiguration =
                RedisCacheConfiguration
                        .defaultCacheConfig()
                        .serializeKeysWith( RedisSerializationContext.SerializationPair.fromSerializer( template.getStringSerializer() ) )
                        .serializeValuesWith( RedisSerializationContext.SerializationPair.fromSerializer( template.getValueSerializer() ) )
                        .disableCachingNullValues()
                        .entryTtl( Duration.ofSeconds(180));

        RedisCacheManager redisCacheManager =
                RedisCacheManager.RedisCacheManagerBuilder
                        .fromConnectionFactory( template.getConnectionFactory() )
                        .cacheDefaults( defaultCacheConfiguration )
                        .transactionAware()
                        .build();
        return redisCacheManager;
    }
}
